package com.bsdsma.visonManagementSystemapp.interceptor;

import com.bsdsma.visonManagementSystemapp.entity.User;
import com.bsdsma.visonManagementSystemapp.entity.Student;
import com.bsdsma.visonManagementSystemapp.entity.Teacher;
import com.bsdsma.visonManagementSystemapp.constants.TokenConstants;
import com.bsdsma.visonManagementSystemapp.utils.LocalUtils;
import com.bsdsma.visonManagementSystemapp.utils.RedisMockUtils;
import com.bsdsma.visonManagementSystemapp.mapper.StudentMapper;
import com.bsdsma.visonManagementSystemapp.mapper.TeacherMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.lang.NonNull;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class UserInterceptor implements HandlerInterceptor {

    private final StudentMapper studentMapper;
    private final TeacherMapper teacherMapper;

    @Autowired
    public UserInterceptor(StudentMapper studentMapper, TeacherMapper teacherMapper) {
        this.studentMapper = studentMapper;
        this.teacherMapper = teacherMapper;
    }

    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws Exception {
        log.info("UserInterceptor preHandle");
        Object uidObj = request.getAttribute(TokenConstants.UID);
        if(null != uidObj){
            Long uid = (Long) uidObj;
            User user = RedisMockUtils.getUser(uid);
            if(null != user){
                // Load school relationship for students and teachers
                if (user instanceof Student) {
                    user = studentMapper.selectByIdWithSchool(user.getId());
                } else if (user instanceof Teacher) {
                    user = teacherMapper.selectByIdWithSchool(user.getId());
                }
                LocalUtils.setUser(user);
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler, Exception ex) throws Exception {
        log.info("UserInterceptor afterCompletion");
        LocalUtils.clearUser();
    }
}
